<template>
  <el-dialog
    v-model="dialogVisible"
    title="订单详情"
    width="70%"
    top="5vh"
    @close="handleClose"
  >
    <div v-loading="loading" class="detail-container">
      <template v-if="orderDetail">
        <div class="summary-section">
          <div class="left-summary">
            <p>CRMS订单号：{{ orderDetail.saleOrderCode }}</p>
            <div class="status-progress">
              <strong class="status-text">{{ orderDetail.orderStatus }}</strong>
              <span>已生产 {{ orderDetail.overallPercentage }}%</span>
              <el-progress
                :percentage="orderDetail.overallPercentage"
                :show-text="false"
                style="width: 150px"
              />
            </div>
          </div>
          <div class="right-steps">
            <OrderTimeLine :orderId="props.orderId"/>
          </div>
        </div>

        <!-- 2. 商品信息表格 -->
        <div class="section-block">
          <h4 class="section-title">商品信息</h4>
          <el-table :data="orderDetail.orderItems" style="width: 100%" row-key="id">
            <el-table-column label="商品" min-width="280">
              <template #default="scope">
                <div class="product-cell">
                  <el-image
                    :src="scope.row.imageUrl"
                    fit="contain"
                    style="width: 60px; height: 60px; flex-shrink: 0"
                  />
                  <div class="product-info">
                    <p class="name">{{ scope.row.productName }}</p>
                    <p class="sn">{{ scope.row.partNumber }}</p>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="productCategory" label="物料类型" width="120" />
            <el-table-column prop="requiredQuantity" label="采购数量 (只)" width="120" />
            <el-table-column label="生产进度" min-width="200">
               <template #default="scope">
                 <div class="progress-cell">
                    <p>已生产: {{ scope.row.produced }}</p>
                    <el-progress 
                      :percentage="scope.row.completionPercentage"
                      :show-text="false"
                    />
                    <p>已完成: {{ scope.row.completionPercentage }}%</p>
                    <el-link 
                      v-if="scope.row.completionPercentage == 100" 
                      type="primary" 
                      :icon="Document"
                      style="margin-top: 5px;"
                      @click="handleViewReport"
                    >
                      查看质量报告
                    </el-link>
                 </div>
               </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 3. 收货人信息 -->
        <div class="section-block">
          <div class="info-grid">
            <div>
              <h4 class="section-title">收货人信息</h4>
              <p>客户名称：{{ orderDetail.customerName }}</p>
              <p>收货人：{{ orderDetail.consigneeName }}</p>
              <p>收货地址：{{ orderDetail.shippingStreetAddress }}</p>
              <p>联系号码：{{ orderDetail.contactPhoneNumber }}</p>
            </div>
            <div>
              <h4 class="section-title">发货配送信息</h4>
              <!-- 这里可以填充发货信息 -->
            </div>
          </div>
        </div>

        <!-- 4. 客户需求 -->
        <div class="section-block">
          <h4 class="section-title">客户需求</h4>
          <p>交货日期：{{ orderDetail.deliveryDate }}</p>
        </div>

        <!-- 5. 客户备注 -->
        <div class="section-block">
          <h4 class="section-title">客户备注</h4>
          <p>{{ orderDetail.remarks || '无' }}</p>
        </div>

      </template>
    </div>
    <QualityReportDialog v-model="reportDialogVisible" />
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, watch, computed } from 'vue';
import {
  ElDialog, ElSteps, ElStep, ElProgress, ElTable, ElTableColumn, ElImage, ElLink,
  vLoading,
} from 'element-plus';
import { Document } from '@element-plus/icons-vue';
import { OrderApi, OrderVO } from '@/api/ordermange';
import OrderTimeLine from '@/components/OrderTimeline.vue';
import QualityReportDialog from '@/components/QualityReportDialog.vue';

// --- Props and Emits ---
const props = defineProps<{
  modelValue: boolean; 
  orderId: string | null;
}>();

const emit = defineEmits(['update:modelValue']);

// --- State ---
const loading = ref(false);
const orderDetail = ref<OrderVO | null>(null);

// computed property for v-model
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val),
});

// 1. 定义一个 ref 来控制弹窗的显示状态，默认为 false (隐藏)
const reportDialogVisible = ref(false);

// 2. 定义一个方法，当点击按钮时，将状态设置为 true
const handleViewReport = () => {
  console.log('正在打开质量报告...');
  reportDialogVisible.value = true;
};

// --- Logic ---

// 模拟API调用
const fetchOrderDetail = async (id: number): Promise<OrderVO> => {
  return await OrderApi.getOrder(id);
};

// 监听orderId的变化，一旦有新的ID就去获取数据
watch([() => props.orderId, () => props.modelValue], ([newId, newModelValue]) => {
  if (newId && newModelValue) {
    loading.value = true;
    fetchOrderDetail(newId)
      .then(data => {
        orderDetail.value = data;
      })
      .catch(err => console.error(err))
      .finally(() => {
        loading.value = false;
      });
  }
}, { immediate: true });

const getStepStatus = (status) => {
  if (status === 'finish') return 'success';
  if (status === 'process') return 'process';
  return 'wait';
};

// 关闭弹窗时清空数据
const handleClose = () => {
  orderDetail.value = null;
};
</script>

<style scoped>
.detail-container {
  font-size: 14px;
  color: #606266;
  line-height: 1.8;
}

.summary-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e4e7ed;
}

.left-summary .status-progress {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-top: 10px;
}
.left-summary .status-text {
  font-size: 18px;
  color: #303133;
}

.right-steps {
  width: 60%;
}

.section-block {
  margin-bottom: 25px;
}

.section-title {
  font-size: 15px;
  color: #303133;
  margin-bottom: 10px;
  padding-bottom: 5px;
  border-bottom: 1px solid #f0f2f5;
}

.product-cell {
  display: flex;
  align-items: center;
  gap: 10px;
}
.product-info .name {
  font-weight: 500;
  color: #303133;
  margin: 0;
}
.product-info .sn {
  color: #909399;
  font-size: 12px;
  margin: 0;
}

.progress-cell p {
  margin: 2px 0;
}

.info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

/* 覆盖Element Plus的默认样式 */
:deep(.el-step__title.is-process) {
  font-weight: bold;
}
:deep(.el-table th.el-table__cell) {
  background-color: #fafafa !important;
}
</style>
